import {ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {
  QuestionOptionDtos,
  QuestionOptions,
  TestQuestionModel,
  TestQuestionService
} from '../../../../core/services/http/test-question/test-question.service';
import {PageHeaderType} from '../../../../share/components/page-header/page-header.component';
import {MyGradesService} from '../../../../core/services/http/exams-manage/my-grades.service';
import {ActivatedRoute, Params} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';


interface OptionsInterface {
  label: string;
  value: string | any;
  checked?: boolean;
}

@Component({
  selector: 'app-wrong-topic-training',
  templateUrl: './wrong-topic-training.component.html',
  styleUrls: ['./wrong-topic-training.component.less']
})
export class WrongTopicTrainingComponent implements OnInit {
  @Output() returnBack: EventEmitter<any>;
  @Input() currentPageNum!: number;
  pageHeaderInfo: Partial<PageHeaderType> = {
    breadcrumb: ['在线考试', '错题训练']
  };
  isDisplay = false;
  nextInit = -1;
  myQuestionBookVo: any;
  ids: any[] = [];
  dataInform: TestQuestionModel = {
    type: -1,
    analysis: '',
    content: '',
    difficultyGrade: -1,
    pictureUrl: '',
    questionBlanks: new Array<number>(),
    questionOptionDtos: new Array<QuestionOptionDtos>(),
    questionOptions: new Array<QuestionOptions>()
  };
  radioValue = '';
  correctCheckValue: any[] = [];
  checkValue: any[] = [];
  correctValue: any;
  checkOptions: OptionsInterface[];

  constructor(private dataService: TestQuestionService, private dataServices: MyGradesService, private cdr: ChangeDetectorRef,
              private activatedRoute: ActivatedRoute, private message: NzMessageService) {
    this.returnBack = new EventEmitter<any>();
    this.checkOptions = [{label: '', value: '', checked: false}];
  }

  returnToList(): void {
    this.returnBack.emit({refesh: false, pageNo: this.currentPageNum});
  }

  onInitParams(): void {
    this.dataServices.getWrongTopicId(this.myQuestionBookVo).subscribe(dusItem => {
      this.ids = [...dusItem];
      this.nextNumber();
    });
  }

  changeCheck(value: object[]): void {
    this.checkValue = [];
    // @ts-ignore
    value.forEach((item: { label: string; value: string; checked: boolean }) => {
      if (item.checked) {
        this.checkValue.push(item.value);
      }
    });
    if (this.ArrayIsEqual(this.checkValue, this.correctCheckValue)) {
      this.isDisplay = false;
      this.message.success('回答正确', {nzDuration: 1000, nzAnimate: true});
    } else {
      this.isDisplay = true;
      this.message.info('答案不正确', {nzDuration: 1000, nzAnimate: true});
    }
  }

  changeRadio(): void {
    if (this.radioValue === this.correctValue) {
      this.isDisplay = false;
      this.message.success('回答正确', {nzDuration: 1000, nzAnimate: true});
    } else {
      this.isDisplay = true;
      this.message.error('又答错了', {nzDuration: 1000, nzAnimate: true});
    }
  }

  nextNumber(): void {
    this.radioValue = '';
    this.checkOptions = [];
    this.nextInit = this.nextInit + 1;
    if (this.nextInit < this.ids.length) {
      this.dataService.getTestQuestionDetail(this.ids[this.nextInit]).subscribe(data => {
        this.dataInform = data;
        data.questionOptions?.forEach(item => {
          if (item.answerFlag) {
            this.correctValue = item.sort;
          }
        });
        if (data.type === 2) {
          this.correctCheckValue = [];
          data.questionOptions?.forEach(check => {
            const objectCheck = {
              label: check.content,
              value: check.sort
            };
            this.checkOptions.push(objectCheck);
            if (check.answerFlag) {
              this.correctCheckValue.push(check.sort);
            }
          });
        }
        this.cdr.detectChanges();
      });
    }
  }

  // tslint:disable-next-line:typedef
  ArrayIsEqual(arr1: any[], arr2: any[]) {
    if (arr1 === arr2) {
      return true;
    } else {
      if (arr1.length !== arr2.length) {
        return false;
      } else {
        for (const i in arr1) {
          if (arr1[i] !== arr2[i]) {
            return false;
          }
        }
        return true;
      }
    }
  }

  ngOnInit(): void {
    this.activatedRoute.params.subscribe((queryParam: Params) => {
      this.myQuestionBookVo = {
        pageNum: 0,
        pageSize: 0,
        questionTestId: queryParam['questionTestId'],
        userId: queryParam['userId'],
      };
    });
    this.onInitParams();
  }
}
